const express = require('express');
const router = express.Router();
const dbConfig = require('../db.js')
const mysql = require('mysql');
const sql = require('../sql.js')

const multiparty = require('multiparty');

var connection = mysql.createConnection(dbConfig)
connection.connect();

router.use('/username',(req,res,next)=>{
	let username = req.body.username;
	
	connection.query(sql.user.queryUsername,username,(err,result,fields)=>{
		if(err){
			console.log(err);
			return res.sendStatus(500)
		}
		
		if(result.length == 0){
			res.send('no')
		}else{
			res.send('has')
		}
		
	})
})
router.use('/register',(req,res,next)=>{
	let u = req.body;
	console.log(u)
	let r = [u.username,u.password,u.name,u.answer,u.mail]
	connection.query(sql.user.register,r,(err,result,fields)=>{
		if(err){
			console.log(err);
			return res.sendStatus(500)
		}
		res.send(200);
	})
})
router.use('/login',(req,res,next)=>{
	let u = req.body;
	let l = [u.username,u.password,u.level];
	connection.query(sql.user.login,l,(err,result,fields)=>{
		if(err){
			console.log(err);
			return res.sendStatus(500)
		}
		res.status(200).send(result)
		
	})
})
// 插入行驶表信息
router.post('/insertDriving',(req,res,next)=>{
	let d = req.body;
	let driving = [d.user_id,d.car_id,d.dep_place_lon,d.dep_place_lat,d.des_lon,d.des_lat,d.speed]  

	connection.query(sql.driving.insertDriving,driving,(err,result,fields)=>{
		if(err){
			console.log(err)
			return res.sendStatus(500)
		}
		return res.send('ok')
	})
})
// 删除行驶表信息
router.get('/deleteDriving',(req,res,next)=>{
	let user_id = req.query.id;
	connection.query(sql.driving.deleteDriving,user_id,(err,result,fields)=>{
		if(err){
			console.log(err)
		return	res.sendStatus(500)
		}
		return res.send('ok')
	})
})
module.exports = router;